package com.chlp.core.framework.codeGenerator.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.chlp.core.framework.codeGenerator.entity.BasisInfo;
import com.chlp.core.framework.codeGenerator.entity.JsonResult;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * Copyright: Copyright (c) 2019
 *
 * <p>说明：  创建文件</P>
 * Modification History:
 * Date         	Author          Version          Description
 * ---------------------------------------------------------------*
 * 2019年4月9日      		flying-cattle   v3.0.0           initialize
 */
class FreemarkerUtil {

	static JsonResult createFile(BasisInfo dataModel, String templateName, String filePath) {
		JsonResult result = new JsonResult();
		FileWriter out = null;
		String fileName = dataModel.getEntityName() + messageStr(templateName);
		try {
			// 通过FreeMarker的Confuguration读取相应的模板文件
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
			// 设置模板路径
			configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/freemarker");
			// 设置默认字体
			configuration.setDefaultEncoding("utf-8");
			// 获取模板
			Template template = configuration.getTemplate(templateName);
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			file.createNewFile();
//			if(!file.exists()) {
//            }else {
//            	result.setCode(-1);
//            	result.setMessage("已经存在"+fileName);
//            	return result;
//            }

			//设置输出流
			out = new FileWriter(file);
			//模板输出静态文件
			template.process(dataModel, out);
			result.setCode(1);
			result.setMessage("创建" + fileName + "成功");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		result.setCode(-1);
		result.setMessage("创建" + fileName + "失败");
		return result;
	}

	private static String messageStr(String name) {
		if ("entity.ftl".equals(name)) {
			name = ".java";
		}
		if ("dao.ftl".equals(name)) {
			name = "Dao.java";
		}
		if ("mapper.ftl".equals(name)) {
			name = "Mapper.xml";
		}
		if ("service.ftl".equals(name)) {
			name = "Service.java";
		}
		if ("serviceImpl.ftl".equals(name)) {
			name = "ServiceImpl.java";
		}
		if ("controller.ftl".equals(name)) {
			name = "Controller.java";
		}
		if ("pageBean.ftl".equals(name)) {
			name = "PageBean.java";
		}
		return name;
	}
}
